package com.greet.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.greet.constant.JwtClaimsConstant;
import com.greet.constant.MessageConstant;
import com.greet.dto.UserLoginDTO;
import com.greet.entity.User;
import com.greet.exception.LoginFailedException;
import com.greet.mapper.UserMapper;
import com.greet.properties.JwtProperties;
import com.greet.properties.WeChatProperties;
import com.greet.service.UserService;
import com.greet.utils.HttpClientUtil;
import com.greet.utils.JwtUtil;
import com.greet.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //调用微信服务接口，获得当前微信用户的openid
        String openId = getOpenid(userLoginDTO);

        //判断openid是否为空为空登录失败
        if (openId == null || openId == ""){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //判断当前用户是否为新用户
        User userQuery = userMapper.selectByOpenid(openId);
        if (userQuery == null) {
            //如果是新用户，自动完成注册
            userQuery = User.builder()
                    .openid(openId)
                    .createTime(LocalDateTime.now()).build();
            Long userId = userMapper.insert(userQuery);
        }
        //得出用户对象

        //为微信用户生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, userQuery.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(), claims);

        //返回数据
        return UserLoginVO.builder().id(userQuery.getId())
                .openid(userQuery.getOpenid())
                .token(token).build();
    }

    private String getOpenid(UserLoginDTO userLoginDTO) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", userLoginDTO.getCode());
        paramMap.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        String openId = jsonObject.getString("openid");
        return openId;
    }
}
